package com.chenchao.thread;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/16 15:01
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javathread.Test2.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 实现Runnable接口方式
 */
public class Test2 implements Runnable {
    public static void main(String[] args) {
        test3();
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            //获取当前线程名称，当前线程对象的线程名称（this也可以不写）
            System.out.println(Thread.currentThread().getName() + "run" + i + "次");
            System.out.println(Thread.currentThread().getName() + "run" + i + "次");
            if (i % 5 == 0 && i != 0) {
                try {
                    System.out.println("子线程休眠");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void test2(){
        Test2 test2 = new Test2();
        //用Runable的实现类进行构造Thread
        Thread thread = new Thread(test2);
        thread.start();
        for (int i = 0; i < 1000; i++) {
            //获取当前线程名称，当前线程对象的线程名称（this也可以不写）
            System.out.println(Thread.currentThread().getName() + "run" + i + "次");
            System.out.println(Thread.currentThread().getName() + "run" + i + "次");
            if (i % 5 == 0 && i != 0) {
                try {
                    System.out.println("主线程休眠");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 使用匿名内部类实现Runable的接口
     */
    public static void test3() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    //获取当前线程名称，当前线程对象的线程名称（this也可以不写）
                    System.out.println(Thread.currentThread().getName() + "run" + i + "次");
                    System.out.println(Thread.currentThread().getName() + "run" + i + "次");
                }
            }
        });
        thread.start();
    }


}
